
const sequelize = require('../config/operateDB');
const {Sequelize, DataTypes, Op} = require('sequelize');
const {setSession, getRequestParams} = require('../utils/utils');
const {wxUrl} = require('../config/wxUrl');
const axios = require('axios');
const {wxConfig} = require('../config/wxConfig');
const { options } = require('svg-captcha');
const { Folders } = require('./folders');
const { Companies } = require('./companies');



const User = sequelize.define('user', {
    id: {
        type: DataTypes.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    nickName: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    // 用户头像。可以是自己上传 也可以是微信的头像
    avatarUrl: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    gender: {
        type: DataTypes.INTEGER,
        allowNull: false,
    },
    province: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    city: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    country: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    openId: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    wechatCode: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    company: {
        type: DataTypes.UUID,
        allowNull: false,
    },
    folderId: {
        type: DataTypes.UUID,
        allowNull: false,
    },
    // 我的关注用户
    attentionIds: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    // 0 普通人，1、公司管理员 2、系统管理员
    permit: {
        type: DataTypes.INTEGER,
        allowNull: false,
    },
}, {

});
async function initUsers() {
    await User.sync();
    const count = await User.count();
    if (0 === count) {
        await User.create({
            id: '6e81b384-dce5-4d58-abf9-56bde96eda25',
            nickName: '超级管理员',
            avatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/UmsCxtYBNYNPue9CoanFJqlG32N6libtlJFhm6icRpJntFrmcqOmbtB13KJicbUFs6qr4PsrvLKLVEmXoMHmzdgZA/132',
            gender: 1,
            province: '重庆市',
            city: '重庆市',
            country: "China",
            openId: 'oAzWv0ek_xxzUzD5bcMKg61qLjK8',
            wechatCode: '',
            company: 'a0a53019-820d-4253-8338-0e6fb09a5e7b',
            folderId: 'bf2d6778-6fc1-46ca-bc66-cc84a7ee4053',
            permit: '2',
        });

        console.log('初始化管理员成功！');
    }
}
initUsers();

const usersModel = {

    checkParams(ctx, params) {
        if (!params.code) {
            ctx.errorParams('微信的临时登录凭证为空！');
            return false;
        }
        // else if (!params.userInfo) {
        //     ctx.errorParams('用户信息为空！');
        //     return false;
        // }
         else  {
            return true;
        }
    },
    async login(ctx) {
        const params = getRequestParams(ctx);

        var isValid = this.checkParams(ctx, params);
        if (!isValid)  return;

        const res = await axios.get(wxUrl.login, {
            params: {
                appid: wxConfig.getConfig().appId,
                secret: wxConfig.getConfig().AppSecret,
                js_code: params.code,
                grant_type: 'authorization_code'
            },
        });
        if (40029 !== res.data.errcode && 40163 !== res.data.errcode) {
            const wxInfo = res.data;

            let user = await this.getUser(wxInfo.openid);
            if (!user && !!params.userInfo) {
                user = await User.create({
                    ...params.userInfo,
                    permit: 0,
                    openId: wxInfo.openid
                });
            }
            setSession(ctx, user);
            console.log(ctx.session.sessionData, 88)
            ctx.success('登录成功', user);
        } else {
            ctx.errorParams('code 有问题！');
        }

        // else {
        //     await User.update({
        //         ...params.userInfo,
        //         permit: 0,
        //         openId: wxInfo.openid
        //     }, {
        //         where: {
        //             openId: wxInfo.openid
        //         },
        //     });
        // }
    },

    async loginOut(ctx) {
        setSession(ctx, null);
        ctx.success('退出登录成功！');
    },

    async getUser(openId) {
        const user = await User.findOne(
            {
                where: {
                    openId: openId
                },
                raw: true,
            }
        );

        return user;
    },
    async getUsersInfo(ctx) {
        const params = getRequestParams(ctx);
        const user = await User.findOne(
            {
                where: {
                    id: params.id
                },
                raw: true,

            }
        );

        const company = await Companies.findOne({
            where: {
                id: user.company,
            },
            raw: true,
        });

        const folder = await Folders.findOne({
            where: {
                id: user.folderId,
            },
            raw: true,
        });

        ctx.success('获取用户信息成功！', {
            ...user,
            companyName: company.name,
            folderName: folder.name,
        });
    },
    async getCaptcha(ctx) {
        const cap = svgCaptcha.create({
            size: 4, // 验证码长度
            width:160,
            height:60,
            fontSize: 50,
            ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1i
            noise: 2, // 干扰线条的数量
            color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
            background: '#eee' // 验证码图片背景颜色
          })
          let img = cap.data // 验证码
          var text = cap.text.toLowerCase() // 验证码字符，忽略大小写
          ctx.session.captcha = text;
          ctx.success('获取验证码成功！', {svg: img});
    },

    async editUser(ctx) {
        const params = ctx.request.body;
        const editId = params.id;
        if (!editId) {
            ctx.errorParams('id不存在！');
        } else {
            //
            const user = await User.findOne({
                where: {
                    id: editId
                },
                raw: true,
            });
            await User.update({
                ...user,
                ...params,
            }, {
                where: {
                    id: editId
                },
            })

            ctx.success('修改成功', {
                id: editId,
            });
        }
    },

    async getUsers(ctx) {
        const params = ctx.query;
        // const count = await Products.count();
        const {offset = 0, limit = 10, keywords = '', companyId, folderId, myAttention} = params;

        const conditions = {
            nickName: {
                [Op.like]: '%' + keywords + '%',
            },
        }
        if (!!companyId) {
            conditions.company = companyId;
        }
        if (!!folderId) {
            conditions.folderId = folderId;
        }

        let resInfo;
        if (1 === myAttention) {

            if (!!ctx.session.sessionData.attentionIds) {
                conditions.id = {
                    [Op.in]: ctx.session.sessionData.attentionIds.split(','),
                }
                resInfo  = await User.findAndCountAll(
                    {
                        where: conditions,
                        limit: parseInt(limit),
                        offset: parseInt(offset),
                        raw: true,
                    }
                );
            } else {
                resInfo = {
                    rows: [],
                    count: 0,
                }
            }
        } else {
            resInfo  = await User.findAndCountAll(
                {
                    where: conditions,
                    limit: parseInt(limit),
                    offset: parseInt(offset),
                    raw: true,
                }
            );
        }

        const {count, rows} = resInfo;
        

        ctx.pageRes({
            limit,
            offset,
            list: rows,
            total: count,
        });
    },

    async delUser(ctx) {
        const deleteIds = (ctx.request.body.ids || '').split(',');
        if (!deleteIds.length) {
            ctx.errorParams('id数组为空！');
        } else {
            await User.destroy({
                where: {
                    id: {
                        [Op.in]: deleteIds,
                    }
                }
            });

            ctx.success('删除成功！', {
                id: deleteIds,
            })
        }
    },

    async addAttention(ctx) {
        const attentionIds = (ctx.request.body.ids || '').split(',');
        console.log(attentionIds)
        if (!attentionIds.length) {
            ctx.errorParams('id数组为空！');
        } else {
            const userId = ctx.session.sessionData.id;
            const user = User.findOne({
                where: {
                    id: userId,
                }
            });
            let newAttentions = [];
            if (user.attentionIds) {
                newAttentions.push(...user.attentionIds.split(','));
            }
            newAttentions.push(...attentionIds);

            await User.update({
                ...user,
                attentionIds: newAttentions.join(),
            },{
                where: {
                    id: userId
                }
            });

            ctx.success('关注成功', {
                id: attentionIds,
            });
        }
    },
    async quitAttention(ctx) {
        const attentionIds = (ctx.request.body.ids || '').split(',');
        if (!attentionIds.length) {
            ctx.errorParams('id数组为空！');
        } else {
            const userId = ctx.session.sessionData.id;
            const user = User.findOne({
                where: {
                    id: userId,
                }
            });
            let newAttentions = [];
            if (user.attentionIds) {
                user.attentionIds.split(',').forEach(id => {
                    if(-1 === attentionIds.indexOf(id)) {
                        newAttentions.push(id);
                    }
                });
            } else {
                ctx.errorParams('并没有关注该用户！');
            }

            await User.update({
                ...user,
                attentionIds: newAttentions.join(),
            },{
                where: {
                    id: userId
                }
            });

            ctx.success('取消关注成功', {
                id: attentionIds,
            });
        }
    }
};


module.exports = {
    usersModel,
    User,
};
